package com.ananjt.system.user.service.impl;

import com.ananjt.system.entity.SpMenu;
import com.ananjt.system.entity.SpUser;
import com.ananjt.system.user.mapper.SpMenuMapper;
import com.ananjt.system.user.service.SpMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenanhai
 * @since 2020-03-17
 */
@Service
public class SpMenuServiceImpl extends ServiceImpl<SpMenuMapper, SpMenu> implements SpMenuService {

    @Override
    public List<SpMenu> queryMenuByUserId(SpUser spUser) {

        List<SpMenu> menuList = baseMapper.queryMenuByUserId(spUser);

        Map<String, SpMenu> map = new HashMap<>();
        if (menuList != null && menuList.size() > 0) {
            map = menuList.stream().collect(Collectors.toMap(SpMenu::getId, SpMenu -> SpMenu, (oldValue, newValue) -> oldValue));
        }
        List<String> listRemove = new ArrayList<>();

        for (Map.Entry<String, SpMenu> entry : map.entrySet()) {
            SpMenu menu = entry.getValue();
            String sParentId = menu.getParentId();
            SpMenu menuTree = map.get(sParentId);
            if (menuTree != null) {
                if (menuTree.getChildren() == null) {
                    menuTree.setChildren(new ArrayList<SpMenu>());
                }
                menuTree.getChildren().add(menu);
                listRemove.add(entry.getKey());
            }
        }
        List<SpMenu> menus = new ArrayList<>();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            if (!listRemove.contains(key)) {
                menus.add(map.get(key));
            }
        }
        return menus;
    }
}
